<template>
  <div class="cash-manage">
    <!-- ✅ 搜索区域 -->
    <div class="search-bar">
      <el-input
        v-model="searchForm.merchantNameInput"
        placeholder="请输入商家名称"
        clearable
        class="search-item"
      />

      <el-select
        v-model="searchForm.statusInput"
        placeholder="请选择状态"
        clearable
        class="search-item"
      >
        <el-option label="待打款" value="pending" />
        <el-option label="已打款" value="paid" />
      </el-select>

      <el-button type="primary" @click="handleSearch" class="search-item-button"> 搜索 </el-button>
    </div>

    <!-- ✅ 表格（支持横向滚动） -->
    <div class="table-wrapper">
      <el-table :data="pagedList" border style="width: 100%">
        <el-table-column prop="id" label="提现单ID" min-width="80" />

        <el-table-column prop="merchantName" label="商家名称" min-width="140" />

        <el-table-column prop="phone" label="手机号" min-width="140" />

        <!-- ✅ 账户信息列 -->
        <el-table-column label="收款信息" min-width="500">
          <template #default="{ row }">
            <div class="payline">
              <span>收款人：{{ row.receiver || '-' }}</span>
              <span class="divider">|</span>
              <span>账户：{{ row.bankAccount || '-' }}</span>
              <span class="divider">|</span>
              <span>开户行：{{ row.bankName || '-' }}</span>

              <el-button
                v-if="row.bankAccount"
                text
                size="small"
                class="copy-btn"
                @click="copyText(row.bankAccount)"
              >
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="amount" label="提现金额" min-width="120">
          <template #default="{ row }">{{ row.amount }} 元</template>
        </el-table-column>

        <el-table-column prop="createTime" label="提现时间" min-width="180" />

        <el-table-column label="当前状态" min-width="120">
          <template #default="{ row }">
            <el-tag :type="row.status === 'pending' ? 'warning' : 'success'">
              {{ row.status === 'pending' ? '待打款' : '已打款' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" min-width="150">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              :disabled="row.status === 'paid'"
              @click="confirmMarkAsPaid(row)"
            >
              {{ row.status === 'pending' ? '打款完成' : '已打款' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- ✅ 分页 -->
    <div class="pagination-wrap">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="filteredList.length"
        :page-size="pageSize"
        v-model:current-page="currentPage"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getWithdrawMessages, updateWithdrawStatus, type WithdrawMessage } from '@/api/cash'

/* ✅ 原始列表数据 */
const withdrawList = ref<WithdrawMessage[]>([])

/* ✅ 搜索表单（临时） */
const searchForm = ref({
  merchantNameInput: '',
  statusInput: ''
})

/* ✅ 真正过滤用参数 */
const filterKeyword = ref('')
const filterStatus = ref<'pending' | 'paid' | ''>('')

/* ✅ 分页 */
const currentPage = ref(1)
const pageSize = ref(10)

/* ✅ 过滤后的数据 */
const filteredList = computed(() => {
  return withdrawList.value.filter(item => {
    const matchName = filterKeyword.value ? item.merchantName.includes(filterKeyword.value) : true
    const matchStatus = filterStatus.value ? item.status === filterStatus.value : true
    return matchName && matchStatus
  })
})

/* ✅ 分页数据 */
const pagedList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredList.value.slice(start, start + pageSize.value)
})

/* ✅ 点击搜索 */
function handleSearch() {
  filterKeyword.value = searchForm.value.merchantNameInput.trim()
  filterStatus.value = searchForm.value.statusInput as '' | 'pending' | 'paid'
  currentPage.value = 1
}

/* ✅ 复制函数 */
function copyText(text: string) {
  navigator.clipboard
    .writeText(text)
    .then(() => ElMessage.success('复制成功'))
    .catch(() => ElMessage.error('复制失败'))
}

/* ✅ 加载数据 */
async function loadData() {
  withdrawList.value = await getWithdrawMessages()
}

/* ✅ 标记为已打款（带商家名称和打款金额提示） */
async function confirmMarkAsPaid(row: WithdrawMessage) {
  try {
    if (row.amount <= 0) {
      ElMessage.info('无待打款金额')
      return
    }
    await ElMessageBox.confirm(
      `确认将「${row.merchantName}」的提现（￥${row.amount.toFixed(2)}）标记为已打款？`,
      '打款确认',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    await updateWithdrawStatus(row.id)
    ElMessage.success('操作成功')
    await loadData()
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('操作失败')
  }
}

onMounted(loadData)
</script>

<style scoped>
.cash-manage {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.search-item {
  flex: 1;
  min-width: 100px;
  max-width: 200px;
}

.search-item-button {
  flex-shrink: 0;
}

.table-wrapper {
  overflow-x: auto;
  background: #fff;
  border-radius: 8px;
  padding: 12px 16px; /* 表格四周内边距，让表格不贴边 */
}

.account-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.account-info .line {
  display: flex;
  align-items: center;
}

.account-info .label {
  color: #666;
  margin-right: 4px;
  flex-shrink: 0;
}

.pagination-wrap {
  display: flex;
  justify-content: flex-start;
}
.payline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 6px;
}

.divider {
  color: #bbb;
  margin: 0 2px;
}

.copy-btn {
  margin-left: 4px;
}
/*
.el-table_row {

} */
</style>
